package pro.cherish.knowledgeutil.common;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-11-02 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：ValidUtilExt
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-11-02 cherish
 */
@Slf4j
public class ValidUtilExt {

    private static Validator validator = (Validation.byProvider(HibernateValidator.class).configure()).failFast(true).buildValidatorFactory().getValidator();

    public static <T> void validate(T obj) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, new Class[0]);
        if (constraintViolations.size() > 0) {
            ConstraintViolation<T> validateInfo = constraintViolations.iterator().next();
            String message = validateInfo.getRootBeanClass().getName() + "-" + validateInfo.getPropertyPath() + "-" + validateInfo.getMessage();
            log.info("校验出错:" + message);
            throw new RuntimeException(validateInfo.getMessage());
        }
    }

}

